package com.fms.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fms.common.vo.Result;
import com.fms.sys.entity.Billin;
import com.fms.sys.entity.User;
import com.fms.sys.service.IBillinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 收入记录表 前端控制器
 * </p>
 *
 * @author fjt
 * @since 2024-04-21
 */
@RestController
@RequestMapping("/billin")
public class BillinController {
    @Autowired
    private IBillinService billinService;

    @GetMapping("/all") // 请求查询所有的数据
    public Result<List<Billin>> getAllBillIn() {
        List<Billin> list = billinService.list(); // userService内置了增删改查方法，调用即可
        return Result.success(list, "查询成功");
    }

    @GetMapping("/list")
    public Result<Map<String, Object>> getBillInList(@RequestParam(value = "theme", required = false) String theme,
            @RequestParam(value = "reason", required = false) String reason,
            @RequestParam(value = "pageNo") Long pageNo,
            @RequestParam(value = "pageSize") Long pageSize,
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @RequestParam(value = "orderType", required = false) String orderType) {
        LambdaQueryWrapper<Billin> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (StringUtils.hasLength(theme)) {
            wrapper.like(Billin::getTheme, theme);
        }
        if (StringUtils.hasLength(reason)) {
            wrapper.eq(Billin::getReason, reason);
        }

        // 默认按消费日期降序
        wrapper.orderByDesc(Billin::getConsumeDate);

        Page<Billin> page = new Page<>(pageNo, pageSize);
        billinService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @PostMapping
    public Result<?> addBillin(@RequestBody Billin billin) {
        billinService.save(billin);
        return Result.success("新增收入记录成功");
    }

    @PutMapping
    public Result<?> updateBillin(@RequestBody Billin billin) {
        billinService.updateById(billin);
        return Result.success("修改收入记录成功");
    }

    // 要根据ID获取对应的用户信息
    @GetMapping("/{id}")
    public Result<Billin> getBillinById(@PathVariable("id") Integer id) {
        Billin billin = billinService.getById(id);
        return Result.success(billin);
    }

    @DeleteMapping("/{id}")
    public Result<Billin> deleteBillinById(@PathVariable("id") Integer id) {
        billinService.removeById(id);
        return Result.success("成功删除收入记录");
    }

}
